const cart = {
	namespaced: true,
	state: {
		/**
		 * image: string[]
		 * id: string
		 * title: string
		 * desc: string
		 * sku: { size: string, color: string },
		 * price: number
		 * count: number
		 * state: boolean
		 */ 
		cartList: uni.getStorageSync('cartList') || []
	},
	getters: {
		allState(state) {
			return state.cartList.every(v => v.state)
		},
		totalPrice(state) {
			return state.cartList.filter(v => v.state)
				.reduce((p, n) => p + n.count * n.price, 0)
		},
		totalCount(state) {
			return state.cartList.reduce((p, n) => p + n.count, 0)
		}
	},
	mutations: {
		saveStorage(state) {
			uni.setStorageSync('cartList', state.cartList)
		},
		addCart(state, payload) {
			const item = state.cartList.find(v => {
				return v.id === payload.id && v.sku.size === payload.sku.size && v.sku.color === payload.sku.color
			});
			if(item) {
				item.count += payload.count
			} else {
				state.cartList.unshift(payload)
			}
			// 数据持久化
			this.commit('cart/saveStorage')
		},
		/** 非常遗憾， 没有对应的 +- 事件 **/
		addCountCart(state, payload) {
			const item = state.cartList.find(v => {
				return v.id === payload.id && v.sku.size === payload.sku.size && v.sku.color === payload.sku.color
			});
			item.count++;
			// 数据持久化
			this.commit('cart/saveStorage')
		},
		subCountCart(state, payload) {
			const item = state.cartList.find(v => {
				return v.id === payload.id && v.sku.size === payload.sku.size && v.sku.color === payload.sku.color
			});
			item.count--;
			// 数据持久化
			this.commit('cart/saveStorage')
		},
		changeCountCart(state, payload) {
			const item = state.cartList.find(v => {
				return v.id === payload.id && v.sku.size === payload.sku.size && v.sku.color === payload.sku.color
			});
			item.count = payload.count;
			// 数据持久化
			this.commit('cart/saveStorage')
		},
		changeStateCart(state, payload) {
			const item = state.cartList.find(v => {
				return v.id === payload.id && v.sku.size === payload.sku.size && v.sku.color === payload.sku.color
			});
			item.state = !item.state
			this.commit('cart/saveStorage')
		},
		deleteCart(state, payload) {
			state.cartList = state.cartList.filter(v => !(v.id === payload.id && v.sku.size === payload.sku.size && v.sku.color === payload.sku.color));
			this.commit('cart/saveStorage')
		},
		changeAllState(state, payload) {
			state.cartList.forEach(v => v.state = payload);
			this.commit('cart/saveStorage')
		}
	},
	actions: {

	}
}

export default cart